package com.example.demo.security;

import com.example.demo.security.service.SecurityResourceServer;
import com.example.demo.security.service.SecurityRoleService;
import com.example.demo.security.bean.SecurityResourceBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 权限配置控制器
 */
@Controller
@RequestMapping("Admin/security")
public class SecurityController {

    private static final  String rootName = "/security/";

    @Value("${config.page.size}")
    private int pageSize;

    @Autowired
    SecurityRoleService roleService;

    @Autowired
    SecurityResourceServer resourceServer;

    /**
     * 获取资源列表
     * @param model
     * @return
     */
    @RequestMapping(value = "resourcelist")
    public String resourceList(@RequestParam(name = "page",required = false) String page, Model model){
        PageRequest pageRequest =null;
        if (null==page){
            pageRequest = new PageRequest(0,pageSize);
       }else{
            pageRequest = new PageRequest(Integer.valueOf(page)-1,pageSize);
        }
        model.addAttribute("resourcelist",resourceServer.getAll(pageRequest));
        return rootName+"resourcelist";
    }


    /**
     * 新增资源
     * @param model
     * @return
     */
    @RequestMapping(value = "addres")
    public String addResource(Model model){
        model.addAttribute("entity",new SecurityResourceBean());
        return rootName+"addresource";
    }


    /**
     * 删除资源
     * @param id
     * @return
     */
    @RequestMapping(value = "delres/{id}")
    public String delResource(@PathVariable int id){
        resourceServer.delEntity(id);
        return "redirect:/Admin/security/resourcelist";
    }

    /**
     * 得到资源
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "editres/{id}")
    public String getResource(@PathVariable int id,Model model){
        model.addAttribute("entity",resourceServer.getById(id));
        return rootName+"addresource";
    }

    /**
     * 保存资源
     * @param resourceBean
     * @param result
     * @return
     */
    @RequestMapping(value = "saveres",method = RequestMethod.POST)
    public String saveResource(@ModelAttribute("entity") @Valid SecurityResourceBean resourceBean, BindingResult result){
        if (result.hasErrors()){
            return rootName+"addresource";
        }
        resourceServer.save(resourceBean);
        return "redirect:/Admin/security/resourcelist";
    }



}
